package com.aggregate.pay.pufa.support.utils;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author Moyq5
 * @date 2017年6月15日
 */
public class AES {
	private static final String KEY_ALGORITHM = "AES";
	private static final String AES_ALGORITHM="SHA1PRNG";
	private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
	
	public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
		//1.构造密钥生成器，指定为AES算法,不区分大小写
		KeyGenerator keygen = KeyGenerator.getInstance(KEY_ALGORITHM);
		//2.根据ecnodeRules规则初始化密钥生成器
		//生成一个128位的随机源,根据传入的字节数组
		//keygen.init(128, new SecureRandom(encodeRules.getBytes()));//Linux下运行java DES解密失败，报javax.crypto.BadPaddingException:Given final block not properly padded
		SecureRandom secureRandom = SecureRandom.getInstance(AES_ALGORITHM);  
		secureRandom.setSeed(key);  
		keygen.init(128, secureRandom);
		//3.产生原始对称密钥
		SecretKey original_key=keygen.generateKey();
		byte [] raw = original_key.getEncoded();
        //5.根据字节数组生成AES密钥
        SecretKey dest_key =new SecretKeySpec(raw, KEY_ALGORITHM);
        Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);
        //7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作，第二个参数为使用的KEY
        cipher.init(Cipher.ENCRYPT_MODE, dest_key);
        /*
		SecretKeySpec skeySpec = new SecretKeySpec(key, KEY_ALGORITHM);
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(1, skeySpec);
		*/
		return cipher.doFinal(data);
	}

	public static byte[] decrypt(byte[] data, byte[] pwd) throws Exception {
		//1.构造密钥生成器，指定为AES算法,不区分大小写
		KeyGenerator keygen=KeyGenerator.getInstance(KEY_ALGORITHM);
		//2.根据ecnodeRules规则初始化密钥生成器
		//生成一个128位的随机源,根据传入的字节数组
		//keygen.init(128, new SecureRandom(encodeRules.getBytes()));//Linux下运行java DES解密失败，报javax.crypto.BadPaddingException:Given final block not properly padded
		
		//防止linux下 随机生成key</code></span>  
		SecureRandom secureRandom = SecureRandom.getInstance(AES_ALGORITHM);  
		secureRandom.setSeed(pwd);  
		keygen.init(128, secureRandom);
		  //3.产生原始对称密钥
		SecretKey original_key=keygen.generateKey();
        //4.获得原始对称密钥的字节数组
		byte [] raw=original_key.getEncoded();
		//5.根据字节数组生成AES密钥
		SecretKey key=new SecretKeySpec(raw, KEY_ALGORITHM);
        //6.根据指定算法AES自成密码器
		Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);
        //7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作，第二个参数为使用的KEY
		cipher.init(Cipher.DECRYPT_MODE, key);
		//8.解密
		return cipher.doFinal(data);
	}

}